package com.hspedu.newData.dmsxl.图;
/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-28 
 * @Version: 1.0
 */

public class LC130被围绕的区域 {

    private int[][] dir = new int[][]{{0,1},{1,0},{-1,0},{0,-1}};
    public void solve(char[][] board) {

        int m = board.length;
        if (m==0) return;
        int n = board[0].length;

        // 遍历边缘的 ‘O’
        for (int i = 0; i < m; i++) {
            dfs(board,i,0);
            dfs(board,i,n-1);

        }
        for (int i = 1; i < n-1; i++) {
            dfs(board,0,i);
            dfs(board,m-1,i);
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'O'){
                    board[i][j] = 'X';
                }else if (board[i][j] == 'A'){
                    board[i][j] = 'O';
                }
            }
        }
    }

    public void dfs(char[][] board,int x,int y){
        if (x<0||y<0||x>=board.length||y>=board[0].length||board[x][y] != 'O'){
            return;
        }
        board[x][y] = 'A';
        for (int i = 0; i < 4; i++) {
            int nextX = x + dir[i][0];
            int nextY = y + dir[i][1];
            dfs(board,nextX,nextY);
        }

    }

}
